﻿namespace SecurityGroupsAdministration
{
    using System;
    using System.Collections.Generic;

    using Microsoft.SharePoint;

    public class TargetFieldsDataCollectionBL
    {
        #region Fields

        List<DepartmentVisibleFields> _AvailableFields;

        #endregion Fields

        #region Properties

        public List<DepartmentVisibleFields> AvailableFields
        {
            get
            {
                if ( _AvailableFields == null )
                    _AvailableFields = new List<DepartmentVisibleFields>( );
                return _AvailableFields;
            }
        }

        #endregion Properties

        #region Methods

        public void CleanDepartmentOrdering( string siteURL )
        {
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList departmentListValues = storeWeb.Lists[ "Department Administration List" ];
                    SPList orderingList = storeWeb.Lists[ "Department Ordering Lookup" ];
                    int i = 1;

                    foreach ( SPListItem item in departmentListValues.Items )
                    {
                        string currentDepartment = item[ "Department Name" ].ToString( );
                        SPQuery getFields = new SPQuery( );
                        getFields.Query = "<Where><Eq><FieldRef Name='Department_x0020_Owner' /><Value Type='Text'>" + currentDepartment + "</Value></Eq></Where><OrderBy><FieldRef Name='Department_x0020_Owner' Ascending='True' /><FieldRef Name='Order_x0020_Number' Ascending='True' /></OrderBy>";
                        SPListItemCollection orderedFields = orderingList.GetItems( getFields );
                        i = 1;
                        if ( orderedFields.Count > 0 )
                        {
                            foreach ( SPListItem itemFields in orderedFields )
                            {
                                itemFields[ "Order Number" ] = i;
                                itemFields.Update( );
                                i++;
                            }
                        }
                    }
                }
            }
        }

        public void DeleteSelectedField( string siteURL, string sourceDepartment, string targetDepartment, string fieldName )
        {
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList departmentFieldsView = storeWeb.Lists[ "Department Access Administration" ];
                    SPQuery sourceUserDepartments = new SPQuery( );
                    sourceUserDepartments.Query = "<Where><And><Eq><FieldRef Name='Department_x0020_Name' /><Value Type='Text'>" + sourceDepartment + "</Value></Eq><And><Eq><FieldRef Name='Target_x0020_List_x0020_Name' /><Value Type='Text'>" + targetDepartment + "</Value></Eq><Eq><FieldRef Name='Field_x0020_Name' /><Value Type='Text'>" + fieldName + "</Value></Eq></And></And></Where>";

                    SPListItemCollection allFieldViews = departmentFieldsView.GetItems( sourceUserDepartments );
                    if ( allFieldViews.Count == 0 )
                        return;
                    allFieldViews[ 0 ].Delete( );

                    DeleteSelectedOrderField( siteURL, sourceDepartment, targetDepartment, fieldName );
                }
            }
        }

        public void DeleteSelectedOrderField( string siteURL, string sourceDepartment, string targetDepartment, string fieldName )
        {
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList orderingList = storeWeb.Lists[ "Department Ordering Lookup" ];
                    SPQuery validateField = new SPQuery( );
                    validateField.Query = "<Where><And><Eq><FieldRef Name='Field_x0020_Name' /><Value Type='Text'>" + fieldName + "</Value></Eq><And><Eq><FieldRef Name='Source_x0020_Department' /><Value Type='Text'>" + targetDepartment + "</Value></Eq><Eq><FieldRef Name='Department_x0020_Owner' /><Value Type='Text'>" + sourceDepartment + "</Value></Eq></And></And></Where>";
                    SPListItemCollection selectedFields = orderingList.GetItems( validateField );
                    if ( selectedFields.Count == 0 )
                        return;
                    else
                        selectedFields[ 0 ].Delete( );
                }
            }
        }

        public bool DoesFieldExistingOrderList( string siteURL, string sourceDepartment, string fieldName, string targetDepartment )
        {
            bool result = true;
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList orderingList = storeWeb.Lists[ "Department Ordering Lookup" ];
                    SPQuery validateField = new SPQuery( );
                    validateField.Query = "<Where><And><Eq><FieldRef Name='Field_x0020_Name' /><Value Type='Text'>" + fieldName + "</Value></Eq><And><Eq><FieldRef Name='Source_x0020_Department' /><Value Type='Text'>" + sourceDepartment + "</Value></Eq><Eq><FieldRef Name='Department_x0020_Owner' /><Value Type='Text'>" + targetDepartment + "</Value></Eq></And></And></Where>";
                    SPListItemCollection selectedFields = orderingList.GetItems( validateField );
                    if ( selectedFields.Count == 0 )
                        result = false;
                }
                return result;
            }
        }

        public void GetAllDepartmentSelectedFields( string siteURL, string sourceDepartment )
        {
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                DepartmentVisibleFields deptFields = new DepartmentVisibleFields( );
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList departmentFieldsView = storeWeb.Lists[ "Department Access Administration" ];
                    SPQuery sourceUserDepartments = new SPQuery( );
                    sourceUserDepartments.Query = "<Where><Eq><FieldRef Name='Department_x0020_Name' /><Value Type='Text'>" + sourceDepartment.Trim( ) + "</Value></Eq></Where><OrderBy><FieldRef Name='Target_x0020_List_x0020_Name' Ascending='True' /><FieldRef Name='Field_x0020_Name' Ascending='True' /></OrderBy>";
                    SPListItemCollection allFieldViews = departmentFieldsView.GetItems( sourceUserDepartments );

                    foreach ( SPItem item in allFieldViews )
                    {
                        deptFields = new DepartmentVisibleFields( );
                        deptFields.SourceDepartmentName = sourceDepartment;
                        deptFields.TargetDepartmentName = item[ "Target Department Name" ].ToString( ).Trim( );
                        deptFields.TargetFieldName = item[ "Field Name" ].ToString( ).Trim( );
                        deptFields.TargetListName = item[ "Target List Name" ].ToString( ).Trim( );
                        deptFields.ReadOnly = false;
            AvailableFields                        .Add( deptFields );
                    }
                }
            }
        }

        public int GetMaxOrderingNumber( string siteURL, string ownerDepartment )
        {
            int result = 1;
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList orderingList = storeWeb.Lists[ "Department Ordering Lookup" ];
                    SPQuery validateField = new SPQuery( );
                    validateField.Query = "<Where><Eq><FieldRef Name='Department_x0020_Owner' /><Value Type='Text'>" + ownerDepartment + "</Value></Eq></Where><OrderBy><FieldRef Name='Order_x0020_Number' Ascending='False' /></OrderBy>";
                    SPListItemCollection selectedFields = orderingList.GetItems( validateField );
                    if ( selectedFields.Count == 0 )
                        result = 1;
                    else
                    {
                        result = int.Parse( selectedFields[ 0 ][ "Order Number" ].ToString( ) );
                        result++;
                    }
                }
                return result;
            }
        }

        public void GetSourceTargetDepartmentSelectedFields( string siteURL, string sourceDepartment, string targetDepartment )
        {
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                DepartmentVisibleFields deptFields = new DepartmentVisibleFields( );
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList departmentFieldsView = storeWeb.Lists[ "Department Access Administration" ];
                    SPQuery sourceUserDepartments = new SPQuery( );
                    sourceUserDepartments.Query = "<Where><And><Eq><FieldRef Name='Department_x0020_Name' /><Value Type='Text'>" + sourceDepartment + "</Value></Eq><Eq><FieldRef Name='Target_x0020_List_x0020_Name' /><Value Type='Text'>" + targetDepartment + "</Value></Eq></And></Where><OrderBy><FieldRef Name='Target_x0020_List_x0020_Name' Ascending='True' /><FieldRef Name='Field_x0020_Name' Ascending='True' /></OrderBy>";

                    SPListItemCollection allFieldViews = departmentFieldsView.GetItems( sourceUserDepartments );

                    foreach ( SPItem item in allFieldViews )
                    {
                        deptFields = new DepartmentVisibleFields( );
                        deptFields.SourceDepartmentName = sourceDepartment;
                        deptFields.TargetDepartmentName = item[ "Target Department Name" ].ToString( ).Trim( );
                        deptFields.TargetFieldName = item[ "Field Name" ].ToString( ).Trim( );
                        deptFields.TargetListName = item[ "Target List Name" ].ToString( ).Trim( );
                        deptFields.ReadOnly = false;
                        AvailableFields.Add( deptFields );
                    }
                }
            }
        }

        public bool IsFieldSelected( string siteURL, string sourceDepartment, string targetDepartment, string fieldName )
        {
            bool results = false;
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList departmentFieldsView = storeWeb.Lists[ "Department Access Administration" ];
                    SPQuery sourceUserDepartments = new SPQuery( );
                    sourceUserDepartments.Query = "<Where><And><Eq><FieldRef Name='Department_x0020_Name'/><Value Type='Text'>" + sourceDepartment + "</Value></Eq><And><Eq><FieldRef Name='Target_x0020_List_x0020_Name' /><Value Type='Text'>" + targetDepartment + "</Value></Eq><Eq><FieldRef Name='Field_x0020_Name' /><Value Type='Text'>" + fieldName + "</Value></Eq></And></And></Where>";

                    SPListItemCollection allFieldViews = departmentFieldsView.GetItems( sourceUserDepartments );
                    if ( allFieldViews.Count > 0 )
                        results = true;
                }
            }
            return results;
        }

        public void SaveSelectedField( string siteURL, string sourceDepartment, string targetDepartment, string targetList, string fieldName )
        {
            SaveSelectedField( siteURL, sourceDepartment, targetDepartment, targetList, fieldName, false );
        }

        public void SaveSelectedField( string siteURL, string sourceDepartment, string targetDepartment, string targetList, string fieldName, bool readOnly )
        {
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPListItem item;
                    SPList departmentFieldsView = storeWeb.Lists[ "Department Access Administration" ];
                    item = departmentFieldsView.Items.Add( );
                    item[ "Title" ] = sourceDepartment;
                    item[ "Department Name" ] = sourceDepartment;
                    item[ "Target List Name" ] = targetList;
                    item[ "Field Name" ] = fieldName;
                    item[ "Target Department Name" ] = targetDepartment;
                    int i = 1;
                    if ( ValidateItemBeforeInsertion( siteURL, sourceDepartment, targetDepartment, fieldName, false ) )
                    {
                        item.Update( );
                        SPListItem orderingItem;
                        SPList orderingList = storeWeb.Lists[ "Department Ordering Lookup" ];
                        if ( !DoesFieldExistingOrderList( siteURL, sourceDepartment, fieldName, targetDepartment ) )
                        {
                            orderingItem = orderingList.Items.Add( );
                            orderingItem[ "Title" ] = fieldName;
                            orderingItem[ "Source Information List" ] = targetDepartment;
                            i = GetMaxOrderingNumber( siteURL, sourceDepartment );
                            orderingItem[ "Order Number" ] = i;
                            orderingItem[ "Field Name" ] = fieldName;
                            orderingItem[ "Source Department" ] = targetDepartment;
                            orderingItem[ "Department Owner" ] = sourceDepartment;
                            orderingItem.Update( );
                            orderingList.Update( );
                        }
                    }
                    else
                        item.Delete( );

                    departmentFieldsView.Update( );
                }
            }
        }

        private bool ValidateItemBeforeInsertion( string siteURL, string sourceDepartment, string targetDepartment, string fieldName, bool readOnly )
        {
            using ( SPSite storeSite = new SPSite( siteURL ) )
            {
                using ( SPWeb storeWeb = storeSite.OpenWeb( ) )
                {
                    SPList departmentFieldsView = storeWeb.Lists[ "Department Access Administration" ];
                    SPQuery sourceUserDepartments = new SPQuery( );
                    sourceUserDepartments.Query = "<Where><And><Eq><FieldRef Name='Department_x0020_Name' /><Value Type='Text'>" + sourceDepartment + "</Value></Eq><And><Eq><FieldRef Name='Target_x0020_List_x0020_Name' /><Value Type='Text'>" + targetDepartment + "</Value></Eq><Eq><FieldRef Name='Field_x0020_Name' /><Value Type='Text'>" + fieldName + "</Value></Eq></And></And></Where>";

                    SPListItemCollection allFieldViews = departmentFieldsView.GetItems( sourceUserDepartments );
                    if ( allFieldViews.Count == 0 )
                        return true;

                    return false;
                }
            }
        }

        #endregion Methods
    }
}